package org.jeecg.modules.fep.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.fep.untils.OrderNumberRule;
import org.jeecg.modules.fep.entity.FepInstallments;
import org.jeecg.modules.fep.entity.FepOrders;
import org.jeecg.modules.fep.entity.FepOrdersProduct;
import org.jeecg.modules.fep.service.IFepInstallmentsService;
import org.jeecg.modules.fep.service.IFepOrdersProductService;
import org.jeecg.modules.fep.service.IFepOrdersService;
import org.jeecg.modules.fep.vo.FepOrdersPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 订单模块
 * @Author: jeecg-boot
 * @Date:   2023-04-14
 * @Version: V1.0
 */
@Api(tags="订单模块")
@RestController
@RequestMapping("/fep/fepOrders")
@Slf4j
public class FepOrdersController {
	@Autowired
	private IFepOrdersService fepOrdersService;
	@Autowired
	private IFepInstallmentsService fepInstallmentsService;
	@Autowired
	private IFepOrdersProductService fepOrdersProductService;
	/**
	 * 分页列表查询
	 *
	 * @param fepOrders
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "订单模块-分页列表查询")
	@ApiOperation(value="订单模块-分页列表查询", notes="订单模块-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<FepOrders>> queryPageList(FepOrders fepOrders,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		QueryWrapper<FepOrders> queryWrapper = QueryGenerator.initQueryWrapper(fepOrders, req.getParameterMap());
		Page<FepOrders> page = new Page<FepOrders>(pageNo, pageSize);
		IPage<FepOrders> pageList = fepOrdersService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param fepOrdersPage
	 * @return
	 */
	@AutoLog(value = "订单模块-添加")
	@ApiOperation(value="订单模块-添加", notes="订单模块-添加")
    @RequiresPermissions("fep:fep_orders:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody FepOrdersPage fepOrdersPage) {

		FepOrders fepOrders = new FepOrders();
		//调用接口生成订单号
		OrderNumberRule numberRule = new OrderNumberRule();
		String orderNo = numberRule.execute();
		log.debug("订单号:{}",orderNo);
		//将随机生成的订单号放入fepOrders中
		fepOrdersPage.setOrderNo(orderNo);

		//已支付金额 从支付详细中取出,并相加
		List<FepInstallments> fepInstallmentsList = fepOrdersPage.getFepInstallmentsList();
		if(fepInstallmentsList!=null && fepInstallmentsList.size()>0) {
			for ( FepInstallments payAmount:fepInstallmentsList) {
				if (fepOrdersPage.getPaidAmount()==null){
					Double amount = payAmount.getAmount();
					fepOrdersPage.setPaidAmount(amount);
			}else {
					Double paidAmount = fepOrdersPage.getPaidAmount();
					//将double转为BigDecimal再相加计算
					BigDecimal bigDecimalPaid = new BigDecimal(Double.toString(paidAmount));
					Double amount = payAmount.getAmount();
					BigDecimal bigDecimalAmount= new BigDecimal(Double.toString(amount));
					BigDecimal add = bigDecimalPaid.add(bigDecimalAmount);
					fepOrdersPage.setPaidAmount(add.doubleValue());
				}
			}

			//未支付额度，由总金额和已支付金额计算
			//总金额
			Double totalPrice = fepOrdersPage.getPayTotalPrice();
			BigDecimal bigDecimalTotal = new BigDecimal(Double.toString(totalPrice));
			//已支付
			Double paidAmount = fepOrdersPage.getPaidAmount();
			BigDecimal bigDecimalPaid = new BigDecimal(Double.toString(paidAmount));
			//未支付
			BigDecimal absAmount = bigDecimalTotal.subtract(bigDecimalPaid);
			fepOrdersPage.setUpaidAmount(absAmount.doubleValue());

            /*	//一个订单包含几种水果，既为添加了几次订单详情（逻辑错误，添加重复数据，正确应该是1，
            得到这样写是重复量的数，应该从表中获取这个信息）
			int quantity = fepOrdersPage.getFepOrdersProductList().size();
			fepOrdersPage.setQuantity(quantity);*/

			fepOrdersPage.setQuantity(0);

			//是否结清判断 o-结清 1-未结清

			if (Double.doubleToLongBits(fepOrdersPage.getPaidAmount())==Double.doubleToLongBits(fepOrdersPage.getPayTotalPrice())){
              fepOrdersPage.setIsSettle(0);

			}else {
				fepOrdersPage.setIsSettle(1);

			}


		}

		BeanUtils.copyProperties(fepOrdersPage, fepOrders);

		fepOrdersService.saveMain(fepOrders, fepOrdersPage.getFepInstallmentsList(),fepOrdersPage.getFepOrdersProductList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param fepOrdersPage
	 * @return
	 */
	@AutoLog(value = "订单模块-编辑")
	@ApiOperation(value="订单模块-编辑", notes="订单模块-编辑")
    @RequiresPermissions("fep:fep_orders:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody FepOrdersPage fepOrdersPage) {
		FepOrders fepOrders = new FepOrders();
		BeanUtils.copyProperties(fepOrdersPage, fepOrders);
		FepOrders fepOrdersEntity = fepOrdersService.getById(fepOrders.getId());
		if(fepOrdersEntity==null) {
			return Result.error("未找到对应数据");
		}
		fepOrdersService.updateMain(fepOrders, fepOrdersPage.getFepInstallmentsList(),fepOrdersPage.getFepOrdersProductList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "订单模块-通过id删除")
	@ApiOperation(value="订单模块-通过id删除", notes="订单模块-通过id删除")
    @RequiresPermissions("fep:fep_orders:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		fepOrdersService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "订单模块-批量删除")
	@ApiOperation(value="订单模块-批量删除", notes="订单模块-批量删除")
    @RequiresPermissions("fep:fep_orders:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fepOrdersService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "订单模块-通过id查询")
	@ApiOperation(value="订单模块-通过id查询", notes="订单模块-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<FepOrders> queryById(@RequestParam(name="id",required=true) String id) {
		FepOrders fepOrders = fepOrdersService.getById(id);
		if(fepOrders==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(fepOrders);

	}

	/**
	 * 通过orderNo查询
	 *
	 * @param orderNo
	 * @return
	 */
	//@AutoLog(value = "付款记录-通过主表orderNo查询")
	@ApiOperation(value="付款记录-通过主表ID查询", notes="付款记录-通过主表orderNo查询")
	@GetMapping(value = "/queryFepInstallmentsByOrderNo")
	public Result<IPage<FepInstallments>> queryFepInstallmentsListByOrderNo(@RequestParam(name="id",required=true) String orderNo) {

		List<FepInstallments> fepInstallmentsList = fepInstallmentsService.selectByOrderNo(orderNo);
		IPage <FepInstallments> page = new Page<>();
		page.setRecords(fepInstallmentsList);
		page.setTotal(fepInstallmentsList.size());
		return Result.OK(page);
	}
	/**
	 * 通过id查询
	 *
	 * @param orderNo
	 * @return
	 */
	//@AutoLog(value = "订单详情-通过主表orderNo查询")
	@ApiOperation(value="订单详情-通过主表orderNo查询", notes="订单详情-通过主表orderNo查询")
	@GetMapping(value = "/queryFepOrdersProductByOrderNo")
	public Result<IPage<FepOrdersProduct>> queryFepOrdersProductListByOrderNo(@RequestParam(name="id",required=true) String orderNo) {
		List<FepOrdersProduct> fepOrdersProductList = fepOrdersProductService.selectByOrderNo(orderNo);
		IPage <FepOrdersProduct> page = new Page<>();
		page.setRecords(fepOrdersProductList);
		page.setTotal(fepOrdersProductList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fepOrders
    */
    @RequiresPermissions("fep:fep_orders:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FepOrders fepOrders) {
      // Step.1 组装查询条件查询数据

      QueryWrapper<FepOrders> queryWrapper = QueryGenerator.initQueryWrapper(fepOrders, request.getParameterMap());

      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据

      List<FepOrders>  fepOrdersList = fepOrdersService.list(queryWrapper);


      // Step.3 组装pageList
      List<FepOrdersPage> pageList = new ArrayList<FepOrdersPage>();
      for (FepOrders main : fepOrdersList) {
          FepOrdersPage vo = new FepOrdersPage();
          BeanUtils.copyProperties(main, vo);
          List<FepInstallments> fepInstallmentsList = fepInstallmentsService.selectByOrderNo(main.getOrderNo());
          vo.setFepInstallmentsList(fepInstallmentsList);
          List<FepOrdersProduct> fepOrdersProductList = fepOrdersProductService.selectByOrderNo(main.getOrderNo());
          vo.setFepOrdersProductList(fepOrdersProductList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "订单模块列表");
      mv.addObject(NormalExcelConstants.CLASS, FepOrdersPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单模块数据", "导出人:"+sysUser.getRealname(), "订单模块"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("fep:fep_orders:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<FepOrdersPage> list = ExcelImportUtil.importExcel(file.getInputStream(), FepOrdersPage.class, params);
              for (FepOrdersPage page : list) {
                  FepOrders po = new FepOrders();
                  BeanUtils.copyProperties(page, po);
                  fepOrdersService.saveMain(po, page.getFepInstallmentsList(),page.getFepOrdersProductList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  *
	  * @param year
	  * @return
	  */

	 @ApiOperation(value="统计年总销售额", notes="统计年总销售额")
	 @GetMapping(value = "/allSalesTotal")
	public Result<FepOrders> getTotalTurnover(@RequestParam(name="year",required=true) String  year){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("sum(pay_total_price) as sumAll");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y')",year);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("不存在当前年份的数据");

		 }else{
			 return Result.OK(ord);
		 }
	}

	 @ApiOperation(value="统计年度销售额", notes="统计年度12个月的销售额")
	 @GetMapping(value = "/monthlySales")
	 public Result<List<FepOrders>> getMonthlySales(@RequestParam(name="year", required=true) String year) throws ParseException {
		 List<FepOrders>  monthlySales = new ArrayList<>();
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("MONTH(order_time) as month, SUM(pay_total_price) as sumAll");
		 queryWrapper.eq("YEAR(order_time)", year);
		 queryWrapper.groupBy("MONTH(order_time)");
		 List<Map<String, Object>> results = fepOrdersService.listMaps(queryWrapper);
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		 for (int i = 1; i <= 12; i++) {
			 boolean found = false;
			 FepOrders fepOrders = new FepOrders();
			 for (Map<String, Object> result : results) {
				 int month = (int) result.get("month");
				 if (month == i) {
					 found = true;
					 String date=year+"-"+month;
					 Date dates = formatter.parse(date);
					 double sales = (double) result.get("sumAll");
					 fepOrders.setOrderTime(dates);
					 fepOrders.setSumAll(sales);
					 monthlySales.add(fepOrders);
					 break;
				 }
			 }
			 if (!found) {
				 String date=year+"-"+i;
				 Date dates = formatter.parse(date);
				 fepOrders.setOrderTime(dates);
				 fepOrders.setSumAll(0.00);
				 monthlySales.add(fepOrders);
			 }
		 }
		 return Result.OK(monthlySales);
	 }


	 @ApiOperation(value="统计月销售额", notes="统计月销售额")
	 @GetMapping(value = "/monthAllSalesTotal")
	 public Result<FepOrders> getMonthTotalTurnover(@RequestParam(name="month",required=true) String  month){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("sum(pay_total_price) as sumAll");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y-%m')",month);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("不存在当月的数据");

		 }else{
			 return Result.OK(ord);
		 }
	 }


	 @ApiOperation(value="统计日销售额", notes="统计日销售额")
	 @GetMapping(value = "/dayAllSalesTotal")
	 public Result<FepOrders> getDayTotalTurnover(@RequestParam(name="day",required=true) String  day){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("sum(pay_total_price) as sumAll");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y-%m-%d ')",day);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("不存在当天的数据");

		 }else{
			 return Result.OK(ord);
		 }
	 }

	 @ApiOperation(value="统计年总订单数", notes="统计年总订单数")
	 @GetMapping(value = "/allOrders")
	 public Result<FepOrders> getOrdersCount(@RequestParam(name="year",required=true) String  year){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as orderCount");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y')",year);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当年订单为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }


	 @ApiOperation(value="统计年度的订单数", notes="统计年度12个月的订单数")
	 @GetMapping(value = "/monthlyOrders")
	 public Result<List<FepOrders>> getMonthlyOrders(@RequestParam(name="year", required=true) String year) throws ParseException {
		 List<FepOrders> monthlyOrders = new ArrayList<>();
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("MONTH(order_time) as month, count(*) as orderCount");
		 queryWrapper.eq("YEAR(order_time)", year);
		 queryWrapper.groupBy("MONTH(order_time)");
		 List<Map<String, Object>> results = fepOrdersService.listMaps(queryWrapper);
		 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		 for (int i = 1; i <= 12; i++) {
			 boolean found = false;
			 FepOrders fepOrders = new FepOrders();
			 for (Map<String, Object> result : results) {
				 int month = (int) result.get("month");
				 if (month == i) {
					 found = true;
					 String date=year+"-"+month;
					 Date dates = formatter.parse(date);
					 Object count = result.get("orderCount");
					 Integer orderCount= Integer.parseInt(count.toString());
					 fepOrders.setOrderTime(dates);
					 fepOrders.setOrderCount(orderCount);
					 monthlyOrders.add(fepOrders);
					 break;
				 }
			 }
			 if (!found) {
				 String date=year+"-"+i;
				 Date dates = formatter.parse(date);
				 fepOrders.setOrderTime(dates);
				 fepOrders.setOrderCount(0);
				 monthlyOrders.add(fepOrders);
			 }
		 }
		 return Result.OK(monthlyOrders);
	 }

	 @ApiOperation(value="统计月订单数", notes="统计月订单数")
	 @GetMapping(value = "/monthAllOrders")
	 public Result<FepOrders> getMonthOrdersCount(@RequestParam(name="month",required=true) String  month){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as orderCount");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y-%m')",month);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当月订单为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }

	 @ApiOperation(value="统计日订单数", notes="统计日订单数")
	 @GetMapping(value = "/dayAllOrders")
	 public Result<FepOrders> getDayOrdersCount(@RequestParam(name="day",required=true) String  day){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as orderCount");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y-%m-%d ')",day);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当日订单为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }

	 @ApiOperation(value="统计十日订单数", notes="统计十日订单数")
	 @GetMapping(value = "/lastTenDaysOrders")
	 public Result<List<FepOrders>> getLastTenDaysOrders(@RequestParam(name = "day", required = true) String day) throws ParseException {
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		 LocalDate endDate = LocalDate.parse(day, formatter).plusDays(1);;
		 LocalDate startDate = endDate.minusDays(10);
		 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		 List<FepOrders> results = new ArrayList<>();
		 for (LocalDate currentDate = startDate; currentDate.isBefore(endDate); currentDate = currentDate.plusDays(1)) {
			 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
			 queryWrapper.select("count(*) as orderCount");
			 queryWrapper.eq("DATE_FORMAT (order_time,'%Y-%m-%d ')", currentDate.format(formatter));
			 FepOrders ord = fepOrdersService.getOne(queryWrapper);

			 Date ordertime = simpleDateFormat.parse(currentDate.format(formatter));
			 ord.setOrderTime(ordertime);
			 if (ord == null) {
				 return Result.error("订单数量为0，日期为：" + currentDate.format(formatter));
			 } else {
				 results.add(ord);
			 }
		 }
		 return Result.ok(results);
	 }

	 @ApiOperation(value="统计年支付笔数", notes="统计年支付笔数")
	 @GetMapping(value = "/allPaysCount")
	 public Result<FepInstallments> getPaysCount(@RequestParam(name="year",required=true) String  year){
		 //总收益
		 QueryWrapper<FepInstallments> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as paysCount");
		 queryWrapper.eq("DATE_FORMAT (pay_time,'%Y')",year);

		 FepInstallments ord = fepInstallmentsService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当年支付笔数为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }

	 @ApiOperation(value="统计月支付笔数", notes="统计月支付笔数")
	 @GetMapping(value = "/monthAllPaysCount")
	 public Result<FepInstallments> getMonthPaysCount(@RequestParam(name="month",required=true) String  month){
		 //总收益
		 QueryWrapper<FepInstallments> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as paysCount");
		 queryWrapper.eq("DATE_FORMAT (pay_time,'%Y-%m')",month);

		 FepInstallments ord = fepInstallmentsService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当月支付笔数为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }

	 @ApiOperation(value="统计日支付笔数", notes="统计日支付笔数")
	 @GetMapping(value = "/dayAllPaysCount")
	 public Result<FepInstallments> getDayPaysCount(@RequestParam(name="day",required=true) String  day){
		 //总收益
		 QueryWrapper<FepInstallments> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as paysCount");
		 queryWrapper.eq("DATE_FORMAT (pay_time,'%Y-%m-%d ')",day);

		 FepInstallments ord = fepInstallmentsService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当日支付笔数为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }


	 @ApiOperation(value="统计十日支付笔数", notes="统计十日支付笔数")
	 @GetMapping(value = "/lastTenDaysPaysCount")
	 public Result<List<FepInstallments>> getLastTenDaysPaysCount(@RequestParam(name = "day", required = true) String day) throws ParseException {
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		 LocalDate endDate = LocalDate.parse(day, formatter).plusDays(1);;
		 LocalDate startDate = endDate.minusDays(10);
		 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		 List<FepInstallments> results = new ArrayList<>();
		 for (LocalDate currentDate = startDate; currentDate.isBefore(endDate); currentDate = currentDate.plusDays(1)) {
			 QueryWrapper<FepInstallments> queryWrapper = new QueryWrapper<>();
			 queryWrapper.select("count(*) as paysCount");
			 queryWrapper.eq("DATE_FORMAT (pay_time,'%Y-%m-%d ')", currentDate.format(formatter));
			 FepInstallments ord = fepInstallmentsService.getOne(queryWrapper);

			 Date paytime = simpleDateFormat.parse(currentDate.format(formatter));
			 ord.setPayTime(paytime);
			 if (ord == null) {
				return  Result.error("订单数量为0，日期为：" + currentDate.format(formatter));
			 } else {
				 results.add(ord);
			 }
		 }
		 return Result.ok(results);
	 }

	 @ApiOperation(value="统计年已结清订单数", notes="统计年已结清订单数")
	 @GetMapping(value = "/allSettleOrders")
	 public Result<FepOrders> getSettleCount(@RequestParam(name="year",required=true) String  year){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as orderCount");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y')",year);
		 queryWrapper.eq("is_settle",0);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当年订单为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }


	 @ApiOperation(value="统计年未结清订单数", notes="统计年未结清订单数")
	 @GetMapping(value = "/allNoSettleOrders")
	 public Result<FepOrders> getNoSettleCount(@RequestParam(name="year",required=true) String  year){
		 //总收益
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("count(*) as orderCount");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y')",year);
		 queryWrapper.eq("is_settle",1);

		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 //注意，空指针问题
		 if (ord== null){
			 return Result.error("当年订单为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }

	 @ApiOperation(value="统计年未结清订单占比", notes="统计年未结清订单占比")
	 @GetMapping(value = "/noSettleOrdersRatio")
	 public Result<FepOrders> getNoSettleCountRatio(@RequestParam(name="year",required=true) String  year){
		 // 使用 LambdaQueryWrapper 构建查询条件
		 QueryWrapper<FepOrders> queryWrapper = new QueryWrapper<>();
		 queryWrapper.select("ROUND(100 * COUNT(CASE WHEN is_settle = 1 THEN 1 ELSE NULL END) / COUNT(*)) AS proportion");
		 queryWrapper.eq("DATE_FORMAT (order_time,'%Y')",year);

		 // 计算未结清订单和所有订单的数量百分比
		 FepOrders ord= fepOrdersService.getOne(queryWrapper);

		 if (ord== null){
			 return Result.error("当年订单为0");

		 }else{
			 return Result.OK(ord);
		 }
	 }


	 @ApiOperation(value="统计销量Top水果", notes="统计销量Top10的水果")
	 @GetMapping(value = "/lastTopProductsSales")
	 public Result<List<FepOrders>> getLastTopTenProducts(@RequestParam(name="year",required=true) String  year) {

		 List<FepOrders> fepOrders = fepOrdersService.selectTopProductsSales(year);
		 return Result.ok(fepOrders);
	 }


	 @ApiOperation(value="统计未支付总额Top", notes="统计欠费总额Top10")
	 @GetMapping(value = "/lastTopUpaidTotal")
	 public Result<List<FepOrders>> getLastTopUpaidTotal()  {
		 List<FepOrders> fepOrders = fepOrdersService.selectTopUpaidTotal();
		 return Result.ok(fepOrders);
	 }




 }
